package home;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.text.DecimalFormat;

public class Stock {
	
	private String stockSymbol;
	private double stockPrice;
	
	/**
	 * Constructors
	 * @param stockSymbol
	 * @param stockPrice
	 */
	public Stock(String stockSymbol, double stockPrice) {
		super();
		this.stockSymbol = stockSymbol;
		this.stockPrice = stockPrice;
	}
	
	public Stock() {
		super();
	}

	
	/**
	 * Convenient auxiliary method that takes a double and formats it into ###.## format.
	 * @param val
	 * @return
	 */
	double RoundTo2Decimals(double val) {
        DecimalFormat df2 = new DecimalFormat("###.##");
    return Double.valueOf(df2.format(val));
	}
	
	
	
	/**
	 * Takes in a stockSymbol and a day and returns the price of that stock on the specified day by iterating through the StockHistory.txt file and
	 * identifying the latest price saved of that stock on a given day.
	 * @param stockSymbol
	 * @param day
	 * @return
	 */
	public static double getStockValue(String stockSymbol, int day){
		Double finalPrice = null;
		BufferedReader in = null;
		
		//finds stock value for that day as long as the program was saved on that day.
		try {
			in = new BufferedReader(new FileReader("StockHistory.txt"));
			String singleTransaction;
			finalPrice = -1.0;
			while((singleTransaction = in.readLine()) != null){
				if(singleTransaction.split(",")[0].equals(stockSymbol) && Integer.parseInt(singleTransaction.split(",")[1]) == day){
					finalPrice = Double.parseDouble(singleTransaction.split(",")[2]);
				}
			}
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			System.out.println(e.getMessage());
		}
		
		//If no stock value was recorded for that day, finds closest recorded value from that date..recursively and backwards in time from date asked for
		if(finalPrice == -1.0){
			if(day >= 0){
				finalPrice = getStockValue(stockSymbol, day-1);
			}
			else{
				System.out.println("COULDN'T FIND STOCK HISTORY");
			}
		}
		try {
			in.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return finalPrice;
	}
	
	
	
	
	/**
	 * 
	 * Getters and setters
	 * @return
	 */
	public String getStockSymbol() {
		return stockSymbol;
	}
	public void setStockSymbol(String stockSymbol) {
		this.stockSymbol = stockSymbol;
	}
	public double getStockPrice() {
		return stockPrice;
	}
	public void setStockPrice(double stockPrice) {
		this.stockPrice = RoundTo2Decimals(stockPrice);
	}
	
	@Override
	public String toString() {
		return stockSymbol + "                                                " +
				"                                                        " + stockPrice;
	}

}
